var gulp = require('gulp');
var shell = require('gulp-shell');
var zip = require('gulp-zip');
var del = require('del');
var runSequence = require('gulp-sequence');
var fs = require('fs');

var appVersion = '';
var pkgName = '';
var timestamp = (new Date()).getTime();
var buildVersion = timestamp;

gulp.task('generate-pkg-name', function (cb) {
  var projInfo = fs.readFileSync('./package.json', 'utf-8');
  var jsonObj = JSON.parse(projInfo);
  appVersion = jsonObj.version;
  if (process.env.BUILD_NUMBER) {
    buildVersion = process.env.BUILD_NUMBER;
  }
  pkgName = `${jsonObj.name}_${appVersion}_${buildVersion}.zip`;
  cb();
});

gulp.task('build-prd', shell.task([
  `webpack --display-error-details --config ./build-config/webpack.config.js --env.timestamp=${timestamp} --env.BUILD_ENV=PRD`
]));

gulp.task('build-debug', shell.task([
  `webpack --display-error-details --config ./build-config/webpack.config.js --env.timestamp=${timestamp} --env.BUILD_ENV=DEBUG`
]));

gulp.task('compress', function (cb) {
  gulp.src('dist/**/*.*').pipe(zip(pkgName)).pipe(gulp.dest('dist'));
  cb();
});

gulp.task('clean:all', function (cb) {
  del.sync([
    'dist'
  ], {force: true});
  cb();
});

gulp.task('default', function (cb) {
  runSequence('clean:all', 'build-prd', 'generate-pkg-name', 'compress', cb);
});

gulp.task('build:debug', function (cb) {
  runSequence('clean:all', 'build-debug', 'generate-pkg-name', 'compress', cb);
});
